package com.rfchina.okr.xianren.controller.api;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.tools.DiagnosticCollector;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Clear;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.rfchina.okr.xianren.base.BaseNoLoginController;
import com.rfchina.okr.xianren.manager.MyMoneyManager;
import com.rfchina.okr.xianren.model.ActivityRegion;
import com.rfchina.okr.xianren.model.AreaInfo;
import com.rfchina.okr.xianren.model.CategoryInfo;
import com.rfchina.okr.xianren.model.TaskAccepter;
import com.rfchina.okr.xianren.model.TaskInfo;
import com.rfchina.okr.xianren.model.UserInfo;
import com.rfchina.okr.xianren.model.UserMoney;
import com.rfchina.okr.xianren.model.UserRegionCategory;
import com.rfchina.okr.xianren.util.DateTimeUtil;
import com.rfchina.okr.xianren.util.MoneyObjectType;
import com.rfchina.okr.xianren.util.MyUtil;
import com.rfchina.okr.xianren.util.SqlUtil;

public class TaskInfoController extends BaseNoLoginController {

	// 任务列表
	@Clear(ApiLoginInterceptor.class)
	public void task_info_list() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("size", 50);
		// int
		String sql = "from task_info where 1=1 ";
		List<Object> where = new ArrayList<Object>();
		Integer cat_id = getParaToInt("cat_id");
		sql = SqlUtil.integer(sql, cat_id, "cat_id", where);
		Integer areaid = getParaToInt("areaid");
		sql = SqlUtil.integer(sql, areaid, "areaid", where);
		Integer region_id = getParaToInt("region_id");
		sql = SqlUtil.integer(sql, region_id, "region_id", where);
		// 1 创建 2 正常 10 任务完成,
		Integer status = getParaToInt("status", 2);
		sql = SqlUtil.integer(sql, status, "status", where);
		//是否找满人   1,新建,2开始招人,3招满
		Integer find_status = getParaToInt("find_status", 2);
		sql = SqlUtil.integer(sql, find_status, "find_status", where);
		String title = getPara("title");
		sql = SqlUtil.like(sql, title, "title", where);
		sql += " order  by id desc ";

		String select = "select * ";
		Page<Record> pager = Db.paginate(pageNumber, pageSize, select, sql, where.toArray());

		for (Record object : pager.getList()) {
			object.set("area_info", AreaInfo.dao.findById(object.getInt("areaid")));
			object.set("category_info", CategoryInfo.dao.findById(object.getInt("cat_id")));
			object.set("activity_region", ActivityRegion.dao.findById(object.getInt("region_id")));
		}

		myRenderJson(pager);
	}

	// 任务下单
	public void create_task_info() {
		long uid = loginUid();
		// 1 创建 2 正常 3进行中 10 任务完成,
		int status = 1;
		// 1审批中,2审批通过,3审批不通过
		int auditStatus = 1;
		// 1 初始化,2找人中,3找满
		int findStatus = 1;

		UserInfo user = UserInfo.dao.findById(uid);
		verification(user == null, "系统错误");
		verification(StrKit.isBlank(user.getNickname()), "创建任务前,请设置自己的资料信息!");

		Integer catId = getParaToInt("cat_id");
		CategoryInfo cat = CategoryInfo.dao.findById(catId);

		Integer regionId = getParaToInt("region_id");
		ActivityRegion region = ActivityRegion.dao.findById(regionId);
		verification(region == null, "任务范围不存在" + regionId);

		int areaid = region.getAreaid();
		verification(cat == null, "该分类id不存在" + catId);
		verification(cat.getStatus() != 1, "该分类id已经禁用" + catId);
		// 标题
		String title = getPara("title");
		// 联系方式
		String phone = getPara("phone");
		if (StrKit.isBlank(phone)) {
			phone = user.getPhone();
		}
		String introduction = getPara("introduction");
		verification(StrKit.isBlank(title), "标题不能为空");
		// 份数
		Integer totalCount = getParaToInt("total_count", 1);
		verification(totalCount < 1, "任务份数不能小于1");
		verification(totalCount > 99999, "任务份数不能大于99999");
		// 单个金额
		String single_amount = getPara("single_amount", "0");
		BigDecimal singleAmount = new BigDecimal(single_amount);
		verification(singleAmount.doubleValue() <= 0, "错误:金额小于等于0");

		BigDecimal totalAmount = singleAmount.multiply(BigDecimal.valueOf(totalCount));
		BigDecimal serviceCharge = cat.getServiceCharge();
		verification(serviceCharge.compareTo(BigDecimal.valueOf(0)) < 0, "配置错误,服务费不能为负值!");
		BigDecimal totalPayment = totalAmount.add(serviceCharge);
		// 最后时间 yyyy-MM-dd HH:mm:ss
		String endTime = getPara("end_time",
				DateTimeUtil.formatDateTime(new Date(System.currentTimeMillis() + 3 * 1000L * 3600 * 24)));
		Date lockTime = new Date();
		String appid = getAppid();
		TaskInfo info = new TaskInfo();
		info.setAppid(appid);
		info.setCreateUid(uid);
		info.setCatId(catId);
		info.setAreaid(areaid);
		info.setRegionId(regionId);
		info.setCreateName(user.getNickname());
		info.setPhone(phone);
		info.setIntroduction(introduction);
		info.setCreateTime(lockTime);
		info.setEndTime(
				DateTimeUtil.parseDateTime(endTime, new Date(System.currentTimeMillis() + 3 * 1000L * 3600 * 24)));
		info.setStatus(status);
		info.setAuditStatus(auditStatus);
		info.setFindStatus(findStatus);
		info.setTitle(title);
		info.setServiceCharge(serviceCharge);
		info.setTotalPayment(totalPayment);
		info.setTotalAmount(totalAmount);
		info.setTotalCount(totalCount);
		info.setSingleAmount(singleAmount);
		UserMoney money = UserMoney.dao.findById(uid);
		if (money == null) {
			money = new UserMoney();
			money.setUid(uid);
			money.setLocking(0);
			money.setMoney(BigDecimal.valueOf(0D));
			money.save();
		}

		verification(money.getMoney().compareTo(totalPayment) == -1, "你的余额不足!余额:" + money.getMoney());
		info.save();
		Integer id = info.getId();

		String billAuditComment = "任务订单" + id;

		int serviceFlowId = 0;
		// 手续费
		if (serviceCharge.compareTo(BigDecimal.valueOf(0L)) > 0) {
			BigDecimal serviceMoney = serviceCharge.multiply(BigDecimal.valueOf(-1D));
			serviceFlowId = MyMoneyManager.getInstance().changeMoney(lockTime, uid, id, appid, serviceMoney,
					billAuditComment + "手续费", MoneyObjectType.task_create_service);
		}
		// 闲人的总共收益
		BigDecimal payment = totalAmount.multiply(BigDecimal.valueOf(-1D));
		int flow = MyMoneyManager.getInstance().changeMoney(lockTime, uid, id, appid, payment, billAuditComment,
				MoneyObjectType.task_create);
		info = new TaskInfo();
		info.setId(id);
		info.setMoneyFlowId(flow);
		info.setServiceFlowId(serviceFlowId);
		info.update();
		myRenderJson(id);

	}

	// 任务抢单
	public void rob_task_info() {
		long uid = loginUid();
		// 任务id
		Integer id = getParaToInt("id");

		TaskInfo task = TaskInfo.dao.findById(id);
		verification(task == null, "任务不存在!" + id);
		verification(task.getAuditStatus() != 2, "任务审批中!" + id);
		verification(task.getStatus() != 2, "错误,已经完成或是在审批中!" + id);
		// verification(task.getCreateUid() == uid, "自己不能抢自己的单");

		UserInfo user = UserInfo.dao.findById(uid);
		verification(user == null, "系统错误");
		verification(StrKit.isBlank(user.getNickname()), "抢单前请设置自己的资料信息!");
		TaskAccepter ta = new TaskAccepter();
		ta.setTaskId(id);
		ta.setAppId(getAppid());
		ta.setUid(uid);
		ta.setCreateTime(new Date());
		ta.setEndTime(task.getEndTime());

		ta.setCreateName(user.getNickname());
		ta.setPhone(user.getPhone());
		ta.setSingleAmount(task.getSingleAmount());
		// 状态 1审批 2执行中,3失败,10完成
		Integer status = 2;
		//

		Long count = Db.queryLong("select count(*) from task_accepter where task_id=?  ", id);
		if (count >= task.getTotalCount()) {
			TaskInfo tt = new TaskInfo();
			tt.setId(id);
			tt.setFindStatus(3);
			tt.update();
		}
		verification(count >= task.getTotalCount(), "差一秒,已经被其他人抢先一步!");
		Long count1 = Db.queryLong("select count(*) from task_accepter where task_id=? and uid=? and status!=3", id,
				uid);
		verification(count1 > 0, "一个任务只能抢一次!");

		ta.setStatus(status);
		ta.save();

		myRenderJsonSuccess("抢单成功!");
	}

	// 我接到的任务 抢到的任务 订单列表
	public void my_rob_task_info_list() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("size", 50);

		long uid = loginUid();
		// int
		String sql = "  from task_info t join task_accepter a on t.id=a.task_id where a.uid=" + uid;
		List<Object> where = new ArrayList<Object>();
		Integer cat_id = getParaToInt("cat_id");
		Integer areaid = getParaToInt("areaid");
		Integer region_id = getParaToInt("region_id");
		Integer status = getParaToInt("status", 0);
		String title = getPara("title");
		sql = SqlUtil.integer(sql, region_id, "t.region_id", where);
		sql = SqlUtil.integer(sql, status, "t.status", where);
		sql = SqlUtil.integer(sql, cat_id, "t.cat_id", where);
		sql = SqlUtil.integer(sql, areaid, "t.areaid", where);
		sql = SqlUtil.like(sql, title, "t.title", where);
		sql += " order  by t.id desc ";

		String select = "select t.* ";
		Page<Record> pager = Db.paginate(pageNumber, pageSize, select, sql, where.toArray());
		for (Record object : pager.getList()) {
			object.set("area_info", AreaInfo.dao.findById(object.getInt("areaid")));
			object.set("category_info", CategoryInfo.dao.findById(object.getInt("cat_id")));
			object.set("activity_region", ActivityRegion.dao.findById(object.getInt("region_id")));
		}
		myRenderJson(pager);
	}

	// 我的订单列表
	public void my_task_info_list() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("size", 50);

		long uid = loginUid();
		// int
		String sql = "  from task_info where create_uid=" + uid;
		List<Object> where = new ArrayList<Object>();
		Integer cat_id = getParaToInt("cat_id");
		sql = SqlUtil.integer(sql, cat_id, "cat_id", where);
		Integer areaid = getParaToInt("areaid");
		sql = SqlUtil.integer(sql, areaid, "areaid", where);
		Integer region_id = getParaToInt("region_id");
		sql = SqlUtil.integer(sql, region_id, "region_id", where);
		Integer status = getParaToInt("status", 0);
		sql = SqlUtil.integer(sql, status, "status", where);
		String title = getPara("title");
		sql = SqlUtil.like(sql, title, "title", where);
		sql += " order  by id desc ";

		String select = "select * ";
		Page<Record> pager = Db.paginate(pageNumber, pageSize, select, sql, where.toArray());
		for (Record object : pager.getList()) {
			object.set("area_info", AreaInfo.dao.findById(object.getInt("areaid")));
			object.set("category_info", CategoryInfo.dao.findById(object.getInt("cat_id")));
			object.set("activity_region", ActivityRegion.dao.findById(object.getInt("region_id")));
		}
		myRenderJson(pager);
	}

	// 发起人按键完成任务
	public void finish_task_info() {

		long uid = loginUid();
		Integer id = getParaToInt("id");
		TaskInfo task = TaskInfo.dao.findById(id);
		verification(task == null, "任务不存在!" + id);
		verification(task.getAuditStatus() != 2, "任务审批中!" + id);
		// verification(task.getStatus() != 2, "错误,已经完成或是在审批中!" + id);
		verification(task.getCreateUid() != uid, "非法请求!");
		verification(task.getStatus() == 10, "该任务已经完成,不用在操作!");

		List<TaskAccepter> list = TaskAccepter.dao.find("select * from task_accepter where task_id=? ",id);
		verification(list.isEmpty(), "没有抢单不能设置完成!");
		for (TaskAccepter accepter : list) {
			verification(accepter.getStatus() != 10,
					accepter.getCreateName() + ":" + accepter.getPhone() + " 还没有点击完成任务.");
		}
		int count = task.getTotalCount()-list.size();
		verification(count!=0, "该任务设置失败,还有"+count+"个任务没有完成!");
		
		task.setStatus(10);
		task.setFinishStatus(2);
		task.setRealEndTime(new Date());
		task.update();

		myRenderJsonSuccess("任务成功!");
	}

	// 抢单人按键完成任务
	public void finish_task_accepter() {
		long uid = loginUid();
		// 任务id
		Integer id = getParaToInt("id");
		Integer accepterId = getParaToInt("accepter_id");
		String image = getPara("image", "");
		TaskInfo task = TaskInfo.dao.findById(id);
		verification(task == null, "任务不存在!" + id);
		verification(task.getAuditStatus() != 2, "任务审批中!" + id);
		// verification(task.getStatus() != 2, "错误,已经完成或是在审批中!" + id);
		// verification(task.getCreateUid() == uid, "自己不能抢自己的单");

		TaskAccepter accepter = TaskAccepter.dao.findById(accepterId);
		verification(accepter == null, "不存在!");
		verification(accepter.getTaskId() != id.intValue(), "非法请求!");
		verification(accepter.getUid() != uid, "该任务不是你的!");
		accepter.setEndTime(task.getEndTime());
		accepter.setSingleAmount(task.getSingleAmount());
		accepter.setStatus(10);

		accepter.setFinishImage(image);
		accepter.update();
		myRenderJsonSuccess("任务成功,等待主人检查确认!");

	}

	// 增加我来关联分类和活动区域
	public void add_user_region_category() {

		long uid = loginUid();
		Integer regionId = getParaToInt("region_id", 0);
		Integer catid = getParaToInt("catid", 0);
		Integer areaid = getParaToInt("areaid", 0);
		if (regionId > 0) {
			ActivityRegion region = ActivityRegion.dao.findById(regionId);
			verification(region == null, "活动区域不存在!" + regionId);
			areaid = region.getAreaid();
		}

		AreaInfo area = AreaInfo.dao.findById(areaid);
		verification(area == null, "地区不存在" + areaid);
		CategoryInfo category = CategoryInfo.dao.findById(catid);
		verification(category == null, "分类不存在" + catid);
		verification(category.getStatus() != 1, "该分类已经禁用" + catid);
		String catsql = "select count(*) from category_info where pid=? and status=1 ";
		verification(Db.queryLong(catsql, catid) != 0, "不能选择大分类" + catid);

		UserRegionCategory o = new UserRegionCategory();
		o.setAppid(getAppid());
		o.setStatus(1);
		o.setRegionId(regionId);
		o.setUid(uid);
		o.setUpdateTime(new Date());
		o.setCreateTime(new Date());
		o.setCatid(catid);
		o.setAreaid(areaid);
		o.save();

		myRenderJsonSuccess("增加成功!");
	}

	// 删除关联分类和活动区域
	public void del_user_region_category() {

		long uid = loginUid();
		Long id = getParaToLong("id");
		UserRegionCategory info = UserRegionCategory.dao.findById(id);
		verification(info == null, "不存在" + id);
		verification(info.getUid() != uid, "非法操作!");
		info = new UserRegionCategory();
		info.setId(id);
		info.setStatus(2);
		info.setUpdateTime(new Date());
		info.update();
		myRenderJsonSuccess("删除成功!");
	}

	// 我订阅自动接单技能和地区关系列表
	public void my_user_region_category_list() {
		long uid = loginUid();
		String sql = "select * from user_region_category where uid=? and status=1 ";
		List<UserRegionCategory> list = UserRegionCategory.dao.find(sql, uid);
		for (UserRegionCategory userRegionCategory : list) {
			userRegionCategory.put("area_info", AreaInfo.dao.findById(userRegionCategory.getAreaid()));
			userRegionCategory.put("category_info", CategoryInfo.dao.findById(userRegionCategory.getCatid()));
			userRegionCategory.put("activity_region", ActivityRegion.dao.findById(userRegionCategory.getRegionId()));
		}
		myRenderJson(list);
	}

	// 任务详情
	@Clear(ApiLoginInterceptor.class)
	public void task_info_detail() {
		Integer id = getParaToInt("id");
		TaskInfo task = TaskInfo.dao.findById(id);
		verification(task == null, "任务不存在!" + id);
		String sql = "select * from task_accepter where task_id=?";
		List<TaskAccepter> accepters = TaskAccepter.dao.find(sql, id);
		JSONObject json = new JSONObject();
		json.put("task", task);
		json.put("accepters", accepters);
		json.put("category_info", CategoryInfo.dao.findById(task.getCatId()));
		json.put("area_info", AreaInfo.dao.findById(task.getAreaid()));
		json.put("activity_region", ActivityRegion.dao.findById(task.getRegionId()));
		myRenderJson(json);

	}

	// 分类信息列表
	@Clear(ApiLoginInterceptor.class)
	public void category_info_list() {
		Integer pid = getParaToInt("pid");
		String sql = "select * from category_info where 1=1 ";
		List<Object> where = new ArrayList<Object>();
		sql = SqlUtil.integer(sql, pid, "pid", where);

		List<Record> list = Db.find(sql, where.toArray());
		myRenderJson(list);
	}

	// 地区信息列表
	@Clear(ApiLoginInterceptor.class)
	public void area_info_list() {
		Integer pid = getParaToInt("pid");
		String sql = "select * from area_info where 1=1 ";
		List<Object> where = new ArrayList<Object>();
		sql = SqlUtil.integer(sql, pid, "pid", where);
		List<Record> list = Db.find(sql, where.toArray());
		myRenderJson(list);
	}

	// 活动地区列表
	@Clear(ApiLoginInterceptor.class)
	public void activity_region_list() {
		Integer areaid = getParaToInt("areaid");
		String sql = "select * from activity_region where 1=1 ";
		List<Object> where = new ArrayList<Object>();
		sql = SqlUtil.integer(sql, areaid, "areaid", where);

		List<Record> list = Db.find(sql, where.toArray());
		myRenderJson(list);
	}

}
